//
//  StatusDAL.swift
//  MicroBlog
//
//  Created by  NorthCity on 15/11/21.
//  Copyright © 2015年  NorthCity. All rights reserved.
//

import Foundation
/// 本地缓存数据时间
private let dateCacheTime: NSTimeInterval = 7 * 24 * 60 * 60
/// 微博数据访问层
class StatusDAL {
    
    
    /// 加载微博数据
    class func loadStatus(since_id:Int,max_id:Int,finished:(array:[[String:AnyObject]]?) ->()) {
        //        1 检查本地是否有缓存数据
        let array = checkCacheData(since_id,max_id:max_id)
//                2 如果有返回本地数据
        if array!.count > 0{
            print("有缓存数据")
            finished(array: array)
            return
        }
        //        3 如果没有下载网络数据
        NetWorkTools.sharedTools.loadStatus(sin_id: since_id , max_id: max_id){ (result, error) -> () in
            //            1 判断错误
            if error != nil {
                finished(array:nil)
                return
            }
            //            2 判断数据类型转换
            guard let array = result?["statuses"] as? [[String:AnyObject]] else{
                print("数据格式错误")
                finished(array:nil)
                return
            }
        
        
        //        4 将网络数据保存在本地
           StatusDAL.saveCacheData(array)
        //        5 返回网络数据
            finished(array: array)
    }
}

    
    /// 加载本地数据
    class func checkCacheData(since_id:Int,max_id:Int)->[[String:AnyObject]]?{
//        0 创建数组
        var arrayM = [[String:AnyObject]]()
        guard let userId = UserAccountViewModel.sharedUserAccount.userAccount?.uid else{
            print("用户没有登录")
            return arrayM
        }
        
//        1 准备 sql
        var sql = "SELECT statusId, status, userId FROM T_Status \n"
        sql += "WHERE userId = \(userId)\n"
        if since_id > 0{
            sql += " AND statusId > \(since_id)\n"
        }else if max_id > 0{
            sql += " AND statusId < \(max_id)\n"
        }
        sql += " ORDER BY statusId DESC LIMIT 20;"
        
        print("查询数据 SQL->" + sql)
//        2 执行 SQL 返回结果
        SQLitManager.sharedManager.queue.inDatabase { (db) -> Void in
            guard let rs = db.executeQuery(sql) else{
                return
            }
            
            while rs.next(){
                let data = rs.dataForColumn("status")
//                json 反序列化
                let dict = try! NSJSONSerialization.JSONObjectWithData(data, options: [])
//                追加到数组
                arrayM.append(dict as![String:AnyObject])
            }
        }
        
        return arrayM
    }

    
    /// 保存网络数据
 private class func saveCacheData(array:[[String:AnyObject]]){
        guard let userId = UserAccountViewModel.sharedUserAccount.userAccount?.uid else{
            print("用户没有登录")
            return
        }
        //    1  sql
        /**
        参数列表
        微博数据 id
        微博数据
        用户 id
        */
        let sql = "INSERT OR REPLACE INTO T_Status (statusId, status, userId) VALUES (?, ?, ?);"
        //  2 遍历数组,缓存数据
        SQLitManager.sharedManager.queue.inTransaction { (db, rollback) -> Void in
            for dict in array{
                //        1> 微博 id
                let statusId = dict["id"] as! Int
                //        2> JSON字符串 ->NSData  JSON序列化
                let json = try! NSJSONSerialization.dataWithJSONObject(dict, options: [])
                //        3> 判定是否缓存成功
                if !db.executeUpdate(sql,statusId,json,userId){
                    rollback.memory = true
                    break
                }
                
            }
        }
        print("缓存完成")
    }
    
    /// 清理缓存
    class func clearDataCache() {
        let date = NSDate(timeIntervalSinceNow: -dateCacheTime)
        
        let df = NSDateFormatter()
        df.locale = NSLocale(localeIdentifier: "en")
        df.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        let dateStr = df.stringFromDate(date)
        
        print(dateStr)
    }
    

}

